package test.cei.tallerdda.socket.servidor;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Servidor Socket
 * @author Francisco
 */
public class Server {

	private ServerSocket serverSocket;
	private int port = 9999;

	public Server() throws IOException {
		this.serverSocket = new ServerSocket(port);
	}

	public ServerSocket getServerSocket() {
		return serverSocket;
	}

	public void setServerSocket(ServerSocket serverSocket) {
		this.serverSocket = serverSocket;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void escuchar() throws IOException {
		Socket socket = this.serverSocket.accept();
		new Manejador(socket);
	}

	public class Manejador extends Thread {

		private Socket socket;

		public Manejador(Socket socket) {
			this.socket = socket;
			this.start();
		}

		@Override
		public void run() {
			ObjectInputStream ois;
			try {
				System.out.println("Escuchando...");
				ois = new ObjectInputStream(socket.getInputStream());

				String message = (String) ois.readObject();
				System.out.println("Mensaje del cliente: " + message);

				ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
				oos.writeObject("Mensaje Recibido");

				ois.close();
				oos.close();
				socket.close();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		Server s = new Server();
		while (true)
			s.escuchar();
	}
}